package com.mobile.challenge

import android.app.Application
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.mobile.challenge.api.MobileService
import com.mobile.challenge.bean.BaseBean
import com.mobile.challenge.bean.DataBean
import com.mobile.challenge.exception.MobileException
import com.mobile.challenge.util.SUCCESS_ERROR_CODE
import com.mobile.challenge.util.SUCCESS_ERROR_MSG
import com.mobile.challenge.util.TAG
import com.mobile.frame.mvvmframe.base.BaseModel
import com.mobile.frame.mvvmframe.base.DataViewModel
import io.reactivex.Scheduler
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject

/**
 * created by  shakespace
 * 2020/9/14  23:42
 */
class LoginViewModel @Inject constructor(application: Application, model: BaseModel?) : DataViewModel(application, model) {

    var loginData: MutableLiveData<DataBean> = MutableLiveData()
    var loginError: MutableLiveData<MobileException> = MutableLiveData()

    fun login(username: String, password: String) {

        val subscribe = getRetrofitService(MobileService::class.java).login(username, password)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ response ->
                    if (response.errorCode == SUCCESS_ERROR_CODE && response.errorMsg == SUCCESS_ERROR_MSG) {
                        loginData.value = response.data
                    } else {
                        val exception = MobileException()
                        exception.errorCode = response.errorCode
                        exception.errorMsg = response.errorMsg
                        loginError.value = exception
                        Log.e(this.TAG, "login: login error ")
                    }
                }, {
                    val exception = MobileException()
                    exception.errorCode = "9999"
                    exception.errorMsg = it.message
                    exception.hintMsg = "please try again later "
                    Log.e(this.TAG, "login: login error ")
                    loginError.value = exception
                })
    }

}